package com.keon.jianbao.ui.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.R;
import com.keon.jianbao.adapter.UploadImgAdapter;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.Appraisal;
import com.keon.jianbao.bean.NetWorkImg;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.bean.Tweet;
import com.keon.jianbao.enu.WebType;
import com.keon.jianbao.ui.fragment.TweetCommentGoodListFragment;
import com.keon.jianbao.ui.widget.BottomScrollView;
import com.keon.jianbao.ui.widget.CircleImageView;
import com.keon.jianbao.ui.widget.NoScrollGridView;
import com.keon.jianbao.util.DialogHelp;
import com.keon.jianbao.util.StringUtils;
import com.keon.jianbao.util.TDevice;
import com.keon.jianbao.util.UILUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.apache.http.Header;
import org.json.JSONException;

import java.util.ArrayList;

import butterknife.Bind;

/**
 * Created by keon on 2015/9/9.
 */
public class TweetDetailActivity extends BaseActivity implements BottomScrollView.OnScrollToBottomListener {

    int id;
    Tweet tweet;
    TweetCommentGoodListFragment fragment;
    int commentNum;

    @Bind(R.id.tweet_detail_avatar)
    CircleImageView sdvAvatar;
    @Bind(R.id.tweet_detail_name)
    TextView tvName;
    @Bind(R.id.tweet_detail_time)
    TextView tvTime;
    @Bind(R.id.tweet_detail_content)
    TextView tvContent;
    @Bind(R.id.tweet_detail_imgs)
    NoScrollGridView nsgvImgs;
    @Bind(R.id.tweet_detail_comment)
    TextView tvComment;
    @Bind(R.id.tweet_detail_up)
    TextView tvUp;
    @Bind(R.id.tweet_detail_comment_content)
    EditText etContent;
    @Bind(R.id.tweet_detail_comment_submit)
    Button bSubmit;
    @Bind(R.id.tweet_detail_scrollview)
    BottomScrollView bsvScroolView;
    @Bind(R.id.tweet_detail_price)
    TextView tvPrice;

    SimpleHandler tidingsDetailHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    };

    SimpleHandler addCommentHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    etContent.setText("");
                    TweetDetailActivity.showToast(result.getTips());

//                    replaceFragment(new TweetCommentGoodListFragment());
                    fragment.refresh();
                    tvComment.setText("评论：" + (commentNum++));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler deleteHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    showToast(result.getTips());
                    onBackPressed();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onScrollBottomListener(boolean isBottom) {
        if (isBottom) {
            fragment.next();
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tweet_detail;
    }

    @Override
    protected int getToolBarTitle() {
        return R.string.tweet_detail;
    }

    @Override
    public void initView() {

        tvComment.setOnClickListener(this);
        tvUp.setOnClickListener(this);
        bSubmit.setOnClickListener(this);
        bsvScroolView.setOnScrollToBottomLintener(this);
    }

    @Override
    public void initData() {
        tidingsDetailHandler.setContext(this);
        addCommentHandler.setContext(this);
        deleteHandler.setContext(this);

        showWaitDialog();
        Bundle bundle = getIntent().getExtras();
        id = bundle.getInt("id");
        tweet = (Tweet) bundle.getSerializable("tweet");
        initTweet(tweet);
        if (id > 0) {
//            Api.tidings_detail(id, tidingsDetailHandler);

            replaceFragment(TweetCommentGoodListFragment.TYPE_COMMENT);
        } else {
            showToast(R.string.common_error_network);
            onBackPressed();
        }

    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        switch (i) {
            case R.id.tweet_detail_up:
                replaceFragment(TweetCommentGoodListFragment.TYPE_GOOD);
                break;
            case R.id.tweet_detail_comment:
                replaceFragment(TweetCommentGoodListFragment.TYPE_COMMENT);
                break;
            case R.id.tweet_detail_comment_submit:
                if (!StringUtils.isEmpty(etContent.getText().toString())) {
                    Api.add_comment(id, 2, etContent.getText().toString(), 0, addCommentHandler);
                } else {
                    showToast(R.string.tweet_detail_comment_error_null);
                }
                break;
        }
    }

    private void initGridView(ArrayList<String> imgs) {
        ArrayList<NetWorkImg> data = new ArrayList<>(imgs.size());

        for (int i = 0; i < imgs.size(); i++) {
            NetWorkImg netWorkImg = new NetWorkImg(NetWorkImg.TYPE_COMMON, imgs.get(i), NetWorkImg.ACTION_ZOOM_IN);
            data.add(netWorkImg);
        }
        UploadImgAdapter adapter = new UploadImgAdapter(data);

        nsgvImgs.setAdapter(adapter);
    }

    private void replaceFragment(int type) {
        fragment = new TweetCommentGoodListFragment();

        FragmentTransaction trasection =
                getSupportFragmentManager().beginTransaction();
        if (!fragment.isAdded()) {
            try {
                Bundle bundle = new Bundle();
                bundle.putInt("id", id);
                bundle.putInt("type", type);
                fragment.setArguments(bundle);
                trasection.replace(R.id.tweet_detail_comment_up_list, fragment);
//                trasection.addToBackStack(null);
                trasection.commit();

            } catch (Exception e) {
                // TODO: handle exception
                //AppConstants.printLog(e.getMessage());

            }
        } else
            trasection.show(fragment);

    }

    void initTweet(Tweet tweet) {
//        sdvAvatar.setImageURI(Uri.parse(tweet.getUser_face()));
        ImageLoader.getInstance().displayImage(tweet.getUser_face(), sdvAvatar, UILUtils.getOptions1());
        tvName.setText(tweet.getUser_name());
        tvTime.setText(tweet.getCreate_time());
        tvUp.setText("点赞：" + tweet.getGood());
        commentNum = tweet.getComment();
        tvComment.setText("评论：" + commentNum);
        if (tweet.getPrice() > 0) {
            tvPrice.setText("价格：" + tweet.getPrice());
        } else {
            tvPrice.setVisibility(View.GONE);
        }

        SpannableString ss = new SpannableString("[" + tweet.getAppraisal_category() + "]  " + tweet.getContent());
        ss.setSpan(new ForegroundColorSpan(AppContext.getResource().getColor(R.color.assistTextColor)), 0, tweet.getAppraisal_category().length() + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvContent.setText(ss);

        initGridView(tweet.getImages());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        return super.onCreateOptionsMenu(menu);
        if (tweet.getUser_id() == Integer.parseInt(AppContext.getInstance().getProperty("user.id"))) {
            getMenuInflater().inflate(R.menu.menu_tweet_delete, menu);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.item_tweet_delete:

                DialogHelp.getConfirmDialog(TweetDetailActivity.this, "确定删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Api.delete_tidings(id, deleteHandler);
                    }
                }).show();

                break;
        }
        return true;
    }
}
